package com.rm.zeyou.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.rm.zeyou.constant.CommonConstants;
import com.rm.zeyou.constant.NumberConstants;
import com.rm.zeyou.entity.Partners;
import com.rm.zeyou.exception.ErrorCodeException;
import com.rm.zeyou.exception.ErrorCodeExceptionEnum;
import com.rm.zeyou.mapper.PartnersMapper;
import com.rm.zeyou.response.ApiRestResponse;
import com.rm.zeyou.service.PartnersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rm.zeyou.service.UserService;
import com.rm.zeyou.vo.request.ApplyPartnersVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * <p>
 * 城市合伙人表 服务实现类
 * </p>
 *
 * @author YanYang
 * @since 2025-03-12 15:55:08
 */
@Service
public class PartnersServiceImpl extends ServiceImpl<PartnersMapper, Partners> implements PartnersService {
    @Resource
    private PartnersMapper partnersMapper;
    @Resource
    private UserService userService;

    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public ApiRestResponse<Integer> applyPartners(Long userId, ApplyPartnersVo applyVo) {
        //先查询该用户是否有正在审核或者审核成功的申请
        int applyCount = partnersMapper.selectCount(new LambdaQueryWrapper<Partners>()
                .eq(Partners::getUserId, userId)
                .in(Partners::getAuditStatus, NumberConstants.ZERO_CONSTANTS, NumberConstants.ONE_CONSTANTS)).intValue();
        if (applyCount>0){
            throw new ErrorCodeException(ErrorCodeExceptionEnum.AUDITING);
        }

        userService.checkCode(applyVo.getPartnersTel(),applyVo.getCode(), CommonConstants.APPLY_PARTNER);

        Partners insertPartners = new Partners();
        insertPartners.setUserId(userId);
        insertPartners.setPartnersCity(applyVo.getPartnersCity());
        insertPartners.setManagementExperience(applyVo.getManagementExperience());
        insertPartners.setIsWorked(applyVo.getIsWorked());
        insertPartners.setPartnersName(applyVo.getPartnersName());
        insertPartners.setPartnersTel(applyVo.getPartnersTel());
        insertPartners.setPartnersMail(applyVo.getPartnersMail());
        insertPartners.setIdCardPhoto(applyVo.getIdCardPhoto());
        insertPartners.setPartnersRemark(applyVo.getPartnersRemark());

        return ApiRestResponse.success(partnersMapper.insert(insertPartners));
    }
}
